package com.easy.common.util;
//带过期时间的map
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExpiryMap {
    //用来存储数据的
    private  Map<String,Object> map=new java.util.HashMap<String,Object>();
    //存储数据的有效期
    private Map<String,Long> expiryMap=new java.util.HashMap<String,Long>();
    //检查过期线程(池)
    private ScheduledExecutorService service= Executors.newSingleThreadScheduledExecutor();
    //检查周期
    private long expiryTime=1000*6;
    public ExpiryMap(){
        service.scheduleAtFixedRate(this::clearExpiry,expiryTime,expiryTime,TimeUnit.MILLISECONDS);
    }
    public ExpiryMap(long expiryTime){
        this.expiryTime=expiryTime;
        service.scheduleAtFixedRate(this::clearExpiry,expiryTime,expiryTime,TimeUnit.MILLISECONDS);
    }
    //添加键值对，使用默认过期时间
    public void put(String key,Object value){
        map.put(key,value);
        expiryMap.put(key,System.currentTimeMillis()+expiryTime);
    }
    //添加键值对，指定过期时间
    public void put(String key,Object value,long expiryTime){
        map.put(key,value);
        expiryMap.put(key,System.currentTimeMillis()+expiryTime);
    }
    //获取指定键的值
    public Object get(String key){
        if(expiryMap.get(key)!=null&&expiryMap.get(key)<System.currentTimeMillis()){
            map.remove(key);
            expiryMap.remove(key);
        }
        return map.get(key);
    }
    //删除指定键
    public void remove(String key){
        map.remove(key);
        expiryMap.remove(key);
    }
    //检查是否包含指定键而且未过期
    public boolean containsKey(String key){
        if(expiryMap.get(key)!=null&&expiryMap.get(key)<System.currentTimeMillis()){
            map.remove(key);
            expiryMap.remove(key);
        }
        return map.containsKey(key);
    }
    //清除掉过期的key
    public void clearExpiry(){
        for(String key:expiryMap.keySet()){
            if(expiryMap.get(key)<System.currentTimeMillis()){
                map.remove(key);
                expiryMap.remove(key);
            }
        }
    }
}
